package com.ruoyi.common.utils.file;

import com.ruoyi.common.MultipartFileDto;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;

/**
 * @author TsingYu
 * @version 1.0
 * @date 2025/6/30 15:04
 */
public class StreamToMultipartFileConverter {
    public MultipartFile convertStreamToMultipartFile(InputStream inputStream, String filename) throws IOException {
        // 将输入流转化为字节数组
        byte[] bytes = toByteArray(inputStream);

        // 根据字节数组创建一个临时文件
        File tempFile = createTempFile(bytes, filename);

        // 将临时文件转化为MultipartFile
        return createMultipartFile(tempFile, filename);
    }

    private byte[] toByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        return outputStream.toByteArray();
    }

    private File createTempFile(byte[] bytes, String filename) throws IOException {
        File tempFile = File.createTempFile(filename, null);
        try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            outputStream.write(bytes);
        }
        return tempFile;
    }

    private MultipartFile createMultipartFile(File file, String filename) throws IOException {
        return new MultipartFileDto(filename, new FileInputStream(file));
    }

    public static void main(String[] args) throws IOException {
        // 示例用法
        StreamToMultipartFileConverter converter = new StreamToMultipartFileConverter();
        InputStream inputStream = new ByteArrayInputStream("Hello, World!".getBytes());
        MultipartFile multipartFile = converter.convertStreamToMultipartFile(inputStream, "example.txt");
        System.out.println("Original file name: " + multipartFile.getOriginalFilename());
        System.out.println("Content type: " + multipartFile.getContentType());
    }

}
